package com.lw.leetcode.other.b;

/**
 * 200. 岛屿数量
 *
 * @Author liw
 * @Date 2021/4/30 11:21
 * @Version 1.0
 */
public class NumIslands {

    public static void main(String[] args) {
        NumIslands test = new NumIslands();
        char[][] arr = {{'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'}};
        int i = test.numIslands(arr);
        System.out.println(i);
    }

    public int numIslands(char[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int sum = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                char c = grid[i][j];
                if (c == '1') {
                    sum++;
                    find(grid, i, j, m, n);
                }
            }
        }
        return sum;
    }

    private static void find(char[][] grid, int i, int j, int m, int n) {
        if (i < 0 || i == m || j < 0 || j == n) {
            return;
        }
        if (grid[i][j] == '0') {
            return;
        }
        grid[i][j] = '0';
        find(grid, i - 1, j, m, n);
        find(grid, i + 1, j, m, n);
        find(grid, i, j - 1, m, n);
        find(grid, i, j + 1, m, n);
    }

}
